﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace SES_Server
{
    public class ErrorLogger
    {
        public bool WriteErrorLog(Exception objException)
        {
            string strPathName = GetLogFilePath();
            string strException = string.Empty;
            try
            {
                StreamWriter sw = new StreamWriter(strPathName, true);
                sw.WriteLine("Type        : " + "Error");
                sw.WriteLine("Source      : " + ((objException.Source != null) ? objException.Source.ToString().Trim() : ""));
                sw.WriteLine("Method      : " + ((objException.TargetSite != null) ? objException.TargetSite.Name.ToString().Trim() : ""));
                sw.WriteLine("Date        : " + DateTime.Now.ToLongTimeString());
                sw.WriteLine("Time        : " + DateTime.Now.ToShortDateString());
                sw.WriteLine("Error       : " + ((objException.Message != null) ? objException.Message.ToString().Trim() : ""));
                sw.WriteLine("Stack Trace : " + ((objException.StackTrace != null) ? objException.StackTrace.ToString().Trim() : ""));
                sw.WriteLine("^^-------------------------------------------------------------------^^");
                sw.Flush();
                sw.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }
        private static string GetLogFilePath()
        {
            try
            {
                string baseDir = AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.RelativeSearchPath;
                string retFilePath = baseDir + "\\" + "LogFile.txt";
                if (File.Exists(retFilePath)) return retFilePath;
                else
                {
                    FileStream fs = new FileStream(retFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    fs.Close();
                }
                return retFilePath;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }
    }
}
